package com.huawei.M01.iterator.A25;

/**
 * 两个非重叠子数组的最大和
 *
 * @author zhiwu
 */
public class MaxSumToOverLoop {
    public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
        return Math.max(getMaxSum(nums, firstLen, secondLen), getMaxSum(nums, secondLen, firstLen));

    }

    private int getMaxSum(int[] nums, int secondLen, int firstLen) {
        int sumMax = 0;
        for (int i = 0; i < firstLen; i++) {
            sumMax += nums[i];
        }
        int sumR = 0;
        for ( int i = firstLen; i < firstLen + secondLen; i++) {
            sumR += nums[i];
        }
        int res = sumMax +sumR;
        int maxL = sumMax;
        // 滑动窗口查找最大值
        for (int i = firstLen + secondLen, j = firstLen; i < nums.length; i++, j++) {
            maxL += nums[j] - nums[j - firstLen];
            sumMax = Math.max(sumMax, maxL);
            sumR += nums[i] - nums[j];
            res = Math.max(res, sumMax + sumR);
        }
        return res;
    }
}
